package com.atguigu.distributed.lock.leecode;

/**
 * 删除链表倒数第N个节点
 */
public class RemoveNthFromEnd {
    public ListNode removeNthFromEnd(ListNode head,int n){
        ListNode res = new ListNode(-1);
        res.next = head;
        ListNode cur = head;
        ListNode pre = res;
        ListNode fast = head;
        while (n!=0){
            fast = fast.next;
            n--;
        }
        //快慢指针同步，快指针到达末尾，慢指针就到了倒数第n个位置
        while (fast!=null){
            fast = fast.next;
            pre = cur;
            cur = cur.next;
        }
        pre.next = cur.next;
        return res.next;
    }
    public ListNode removeNthFromEnd2(ListNode head,int n){
        ListNode res = new ListNode(-1);
        res.next = head;
        ListNode cur = head;
        ListNode pre = res;
        ListNode fast = head;
        while(n!=0){
            fast = fast.next;
            n--;
        }
        while (fast!=null){
            fast = fast.next;
            pre = cur;
            cur = cur.next;
        }
        pre.next = cur.next;
        return res.next;
    }
}
